package it.fuesi.synoutils.fragments;

import android.app.Activity;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.model.CategorySeries;
import org.achartengine.renderer.DefaultRenderer;
import org.achartengine.renderer.SimpleSeriesRenderer;

import it.fuesi.synoutils.R;
import it.fuesi.synoutils.activities.MainActivity;
import it.fuesi.synoutils.helpers.FormatHelper;
import it.fuesi.synoutils.model.info.DSMInfo;
import it.fuesi.synoutils.model.info.DSMInfoClientParameters;
import it.fuesi.synoutils.model.info.Volume;
import it.fuesi.synoutils.services.client.ServiceClientFactory;
import it.fuesi.synoutils.services.tasks.info.DSMInfoTask;


/**
 * A simple {@link android.app.Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link it.fuesi.synoutils.fragments.HomeFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link it.fuesi.synoutils.fragments.HomeFragment#newInstance} factory method to
 * create an instance of this fragment.
 *
 */
public class HomeFragment extends BaseFragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_SECTION_NUMBER = "section_number";


    // TODO: Rename and change types of parameters
    private int mSectionNumber;

    private OnFragmentInteractionListener mListener;


    private static int[] COLORS = new int[] { Color.GREEN, Color.BLUE,Color.MAGENTA, Color.CYAN };

    //private static double[] VALUES = new double[] { 10, 11, 12, 13 };

    //private static String[] NAME_LIST = new String[] { "A", "B", "C", "D" };

    private CategorySeries mSeries = new CategorySeries("");

    private DefaultRenderer mRenderer = new DefaultRenderer();

    private GraphicalView mChartView;

    private LinearLayout mChartLayout;



    @Override
    public void onActionRefresh() {
        fetch(true);
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     *
     * @return A new instance of fragment DownloadStationFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static HomeFragment newInstance(int position) {
        HomeFragment fragment = new HomeFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, position);
        fragment.setArguments(args);
        return fragment;
    }
    public HomeFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mSectionNumber = getArguments().getInt(ARG_SECTION_NUMBER);
        }



    }

    private TextView mModel;
    private TextView mRam;
    private TextView mSerial;
    private TextView mUpTime;
    private TextView mVersion;


    private DSMInfo info;

    @Override
    public boolean onBackPressed() {
        final MainActivity main = (MainActivity)getActivity();
        main.quit();
        return true;
    }


    public void setInfo(DSMInfo info){
        this.info = info;
        evalInfo();

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        final View rootView = inflater.inflate(R.layout.fragment_home, container, false);


        mModel = (TextView)rootView.findViewById(R.id.home_model_value);
        mRam = (TextView)rootView.findViewById(R.id.home_ram_value);
        mSerial = (TextView)rootView.findViewById(R.id.home_serial_value);
        mUpTime = (TextView)rootView.findViewById(R.id.home_uptime_value);
        mVersion = (TextView)rootView.findViewById(R.id.home_version_value);

        if(info != null)
            evalInfo();


        mChartLayout = (LinearLayout) rootView.findViewById(R.id.chart);


        return rootView;
    }


    private void evalInfo(){
        mModel.setText(info.getModel());
        mRam.setText("" + info.getRam() + " Mb");
        mSerial.setText(info.getSerial());
        mUpTime.setText(FormatHelper.formatTime(info.getUptime()));
        mVersion.setText(info.getVersion_string());

        refreshChart();
    }

    private void refreshChart(){
        //chart
        mRenderer.setApplyBackgroundColor(false);
        // mRenderer.setBackgroundColor(Color.argb(100, 50, 50, 50));
        mRenderer.setLabelsTextSize(30);
        mRenderer.setMargins(new int[]{20, 30, 15, 0});
        mRenderer.setZoomButtonsVisible(false);
        mRenderer.setStartAngle(90);
        mRenderer.setShowLegend(false);
        mRenderer.setDisplayValues(false);
        mRenderer.setLabelsColor(Color.BLACK);
        mRenderer.setClickEnabled(false);
        mRenderer.setSelectableBuffer(10);
        mRenderer.setZoomEnabled(true);
        mRenderer.setShowLabels(true);
        mRenderer.setLegendTextSize(35);
        mRenderer.setFitLegend(false);
        mRenderer.setPanEnabled(false);



        long used = 0;
        long free = 0;

        if(info.getVolumes() != null){
            for(Volume v : info.getVolumes()){
                v.calculateFree();
                used += v.getUsed();
                free += v.getFree();
            }

            used = used * 1000000;
            free = free * 1000000;

            long total = used + free;

            mSeries.clear();
            mRenderer.removeAllRenderers();

            mSeries.add("Used space (" + FormatHelper.formatFileSize(used) + ")", used);
            SimpleSeriesRenderer rendererUsed = new SimpleSeriesRenderer();
            rendererUsed.setColor(Color.RED);
            mRenderer.addSeriesRenderer(rendererUsed);

            mSeries.add("Free space (" + FormatHelper.formatFileSize(free) + ")", free);
            SimpleSeriesRenderer rendererFree = new SimpleSeriesRenderer();
            rendererFree.setColor(Color.GREEN);
            mRenderer.addSeriesRenderer(rendererFree);

            /*
            mSeries.add("Total (" + FormatHelper.formatFileSize(total) + ")", 0);
            SimpleSeriesRenderer rendererTotal = new SimpleSeriesRenderer();
            rendererTotal.setColor(Color.BLUE);
            mRenderer.addSeriesRenderer(rendererTotal);*/


            if (mChartView == null) {

                mChartView = ChartFactory.getPieChartView(getActivity(), mSeries, mRenderer);
                mChartLayout.addView(mChartView, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT));
            }else
                mChartView.repaint();
        }


    }

    @Override
    public void onStart() {
        super.onStart();
        if(ServiceClientFactory.getSynoConfig() != null && ServiceClientFactory.getSynoConfig().isSet())
            fetch();
    }

    private void fetch(){
        fetch(false);
    }

    private void fetch(boolean expireCache){
        DSMInfoClientParameters params = DSMInfoClientParameters.build(expireCache);

        new DSMInfoTask(getActivity()).execute(params);
    }


    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnFragmentInteractionListener) activity;

        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }

            ((MainActivity) activity).onSectionAttached(
                    getArguments().getInt(ARG_SECTION_NUMBER));
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        return false;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        public void onFragmentInteraction(Uri uri);
    }






}
